package edu.zut.cs.network.runnable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLException;
import java.util.List;

import edu.zut.cs.network.base.BaseMainCase;
import edu.zut.cs.network.entity.Book;
import edu.zut.cs.network.service.BookManager;
import edu.zut.cs.network.service.impl.BookManagerImpl;
import edu.zut.cs.network.socket.JMSProducerThread;


public class ServerRunnable extends BaseMainCase implements Runnable{
	public static final String CHARCODE = "utf-8";

	private Socket socket;
	BookManager bookManager;
	public ServerRunnable(Socket socket) throws SQLException {
		this.socket = socket;
		this.bookManager = new BookManagerImpl();
	}
	private PrintWriter getWriter(Socket socket) throws IOException {//向客户端发数据，向流中写数据
		OutputStream socketOut = socket.getOutputStream();
		return new PrintWriter(socketOut, true);
	}

	private BufferedReader getReader(Socket socket) throws IOException {//接受客户端数据，从流中读数据
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}
	@Override
	public void run() {
		BufferedReader br = null;
		PrintWriter out = null;
		try {
			br = getReader(socket);
			out = getWriter(socket);
			String msString="Hello "+Thread.currentThread().getName()+"! please input tableName：";
			/*服务器写回流中，发送到客户端*/
			out.println(msString);
			//out.flush();
			String msg = null;
			while ((msg = br.readLine()) != null) {								
				logger.info("服务器接收"+Thread.currentThread().getName()+"的消息:" + msg);
				List<Book> bookList = bookManager.getAll(msg);
				/*
				 * 此处可以加多线程
				 * 可以多线程向队列发消息*/
				JMSProducerThread jmsProducerThread=new JMSProducerThread(bookList);//生产者向队列生产消息
				jmsProducerThread.produce();
				
				out.println("发送完毕！");
				out.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (out != null) {
				out.close();
			}
		}
	
		
	}
}
